import React, { Component } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, Table, Modal, Select, DatePicker, Radio } from 'antd';
import styles from './List.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import globalConstant from '../../utils/globalConstant';
import ShowBusinessInfo from './ShowBusinessInfo';


const FormItem = Form.Item;
const { Option } = Select;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;


@connect(({ packageOrder, general, loading }) => ({
  packageOrder,
  general,
  loading: loading.models.packageOrder,
}))
@Form.create()
export default class BusinessOrder extends Component {
  state = {
    id: undefined,
    showBusinessInfoVisible: false,
    selectedRowKeys: [],
    selectedRows: [],
    pageNum: globalConstant.paging.pageNum,
    pageSize: globalConstant.paging.pageSize,
    form: {},
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'packageOrder/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
    dispatch({
      type: 'general/getPackageLists',
    });
    dispatch({
      type: 'general/getDistrictList',
    });
  }
  onSelectChange = (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    this.setState({ selectedRowKeys });
    this.setState({ selectedRows });
  }
  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.state.form,
    };
    this.setState({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
    console.log(params);
    dispatch({
      type: 'packageOrder/fetch',
      payload: params,
    });
  }
  changeOrderType = (e) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'packageOrder/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
        orderType: e.target.value,
      },
    });
  }
  refreshList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'packageOrder/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
  }
  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const rangeValue = fieldsValue.date || undefined;
      dispatch({
        type: 'packageOrder/fetch',
        payload: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.keywordsNames || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          packageId: fieldsValue.package === -1 ? null : Number(fieldsValue.package),
        },
      });
      this.setState({
        form: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.keywordsNames || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          packageId: fieldsValue.package === -1 ? null : Number(fieldsValue.package),
        },
      });
    });
  }
  showInfo = (value) => {
    this.setState({
      showBusinessInfoVisible: true,
      id: value.id,
    });
  };
  handleInfoBusinessModalCancel =() => {
    this.setState({
      showBusinessInfoVisible: false,
    });
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      form:{},
    });
    dispatch({
      type: 'packageOrder/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const districtArray = [{ id: -1, value: '全部' }];
    this.props.general.districtList.map((item) => {
      return (
        districtArray.push({ id: item.id, value: item.districtName })
      );
    });
    const packageArray = [{ id: -1, value: '全部' }];
    this.props.general.packageList.map((item) => {
      return (
        packageArray.push({ id: item.id, value: item.packageName })
      );
    });
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字">
              {getFieldDecorator('keywordsValue')(
                <Input />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="套餐">
              {getFieldDecorator('package')(
                <Select placeholder="请选择">
                  {
                    packageArray.map((item, index) => {
                      return (
                        <Option
                          key={index.toString()}
                          value={item.id}
                        >
                          {item.value}
                        </Option>
                      );
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="筛选时间">
              {getFieldDecorator('date')(
                <DatePicker.RangePicker
                  style={{ width: '100%' }}
                  format={globalConstant.dateFormat}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字类型">
              {getFieldDecorator('keywordsNames')(
                <Select
                  mode="multiple"
                >
                  <Select.Option value="userName">姓名</Select.Option>
                  <Select.Option value="orderNo">订单号</Select.Option>
                  <Select.Option value="packageName">套餐名</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>

          <Col span={8}>
            <FormItem label="区域">
              {getFieldDecorator('districtId')(
                <Select placeholder="请选择">
                  {
                    districtArray.map((item, index) => {
                      return (
                        <Option
                          key={index.toString()}
                          value={item.id}
                        >
                          {item.value}
                        </Option>
                      );
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8} style={{ textAlign: 'right' }}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    const { loading, packageOrder: { packageOrderList } } = this.props;
    const { showBusinessInfoVisible, selectedRowKeys, selectedRows, id } = this.state;
    const columns = [
      {
        title: '用户名',
        dataIndex: 'userName',
      },
      {
        title: '套餐名',
        dataIndex: 'packagesName',
      },
      {
        title: '金额',
        dataIndex: 'orderPrice',
      },
      {
        title: '付款状态',
        dataIndex: 'payStatus',
      },
      {
        title: '推荐人电话',
        dataIndex: 'referencePhone',
      },
      {
        title: '奖金是否发放',
        dataIndex: 'isReferenceReward',
      },
      {
        title: '审核状态',
        dataIndex: 'checkStatusDes',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: '15%',
        render: (text) => {
          return text !== 0 ? moment(text.createTime).format('YYYY-MM-DD') : '日期无效';
        },
      },
      {
        title: '操作',
        key: 'key',
        render: (text, record, index) => {
          return (
            <div key={index.toString()}>
              <Button type="primary" onClick={() => { this.showInfo(text); }} >
                查看详情
              </Button>
            </div>
          );
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: packageOrderList && packageOrderList.totals,
      showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
      ...globalConstant.pagingFormat,
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: record.status,
      }),
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <PageHeaderLayout title="业务订单">
        <div className={styles.tableListOperator}>
          <RadioGroup defaultValue={null} onChange={(e) => { this.changeOrderType(e); }} >
            <RadioButton value={null}>全部</RadioButton>
            <RadioButton value="NETWORK_ORDER_TYPE_NEW ">新买套餐订单</RadioButton>
            <RadioButton value="NETWORK_ORDER_TYPE_CONTINUE">续费订单</RadioButton>
            <RadioButton value="NETWORK_ORDER_TYPE_UP_SPEED ">提速订单</RadioButton>
          </RadioGroup>
        </div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
            {/*<Card>*/}
              {/*<Button*/}
                {/*type="primary"*/}
                {/*onClick={() => { console.log(selectedRows); }}*/}
                {/*disabled={!hasSelected}*/}
              {/*>*/}
                {/*审核*/}
              {/*</Button>*/}
            {/*</Card>*/}
            <Card bordered>
              <Table
                bordered
                rowSelection={rowSelection}
                loading={loading}
                rowKey={record => record.id}
                dataSource={packageOrderList && packageOrderList.items}
                columns={columns}
                pagination={paginationProps}
                onChange={this.handleStandardTableChange}
              />
            </Card>
          </div>
        </Card>
        <Modal
          visible={showBusinessInfoVisible}
          title="查看详情"
          footer={null}
          width="60%"
          onCancel={() => this.handleInfoBusinessModalCancel()}
          destroyOnClose
        >
          <ShowBusinessInfo refreshList={this.refreshList.bind(this)} data={id} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
